import DialogTable from '@/components/lib/DialogTable'
import { FetchApi } from '@/components/lib/tools/hooks/useTableData'
import { sleep } from '@/components/lib/tools/util/time'
import { getDataByPage } from '@/components/lib/utils/array'
import { defineComponent } from 'vue'

interface Goods {
  id: string
  name: string
  price: number
}

const testData: Goods[] = [
  { id: '1', name: '牛奶', price: 5 },
  { id: '2', name: '鸡蛋', price: 1 },
  { id: '3', name: '猪肉', price: 15 }
]

const fetchApi: FetchApi = async ({ page, pageSize }, searchParams) => {
  const data = testData.filter((item) => {
    if (!searchParams.id) {
      return true
    }
    return item.id === searchParams.id
  })
  await sleep(2000)
  return Promise.resolve({
    data: getDataByPage(data, page, pageSize),
    total: data.length
  })
}

export default defineComponent({
  name: 'DialogTableView',
  setup() {
    const handleSubmit = (data) => {
      window.opener.postMessage(
        JSON.stringify({
          action: 'sap-xxx',
          data
        }),
        'http://localhost:8080'
      )
      window.close()
    }
    /* render 函数 */
    return () => {
      return (
        <div>
          <DialogTable
            tableAttrs={{
              rowKey: 'id',
              columns: [
                { title: 'ID', dataIndex: 'id' },
                { title: '商品名', dataIndex: 'name' },
                { title: '价格', dataIndex: 'price' }
              ],
              pagination: {
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`
              },
              rowSelection: {
                type: 'radio'
              }
            }}
            autoUpdate
            fetchApi={fetchApi}
            searchable={true}
            searchKeys={[
              { type: 'text', key: 'id', title: 'ID' },
              { type: 'text', key: 'name', title: '商品名' }
            ]}
            onSubmit={handleSubmit}
          />
        </div>
      )
    }
  }
})
